package edu.xpu.compute.recommend.restful;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import edu.xpu.compute.recommend.common.model.ResponseParam;
import edu.xpu.compute.recommend.entity.SysAdminUser;
import edu.xpu.compute.recommend.entity.SysUser;
import edu.xpu.compute.recommend.service.SysAdminUserService;
import edu.xpu.compute.recommend.service.SysUserService;
import edu.xpu.compute.recommend.vo.LoginUserVo;

@RestController
@RequestMapping(value="restful")
public class IndexRestful {
	@Autowired
	private SysUserService userService;
	@Autowired
	private SysAdminUserService adminUserService;
	
	/**
	 * 用户注册
	 * @param sysUser
	 * @return
	 */
	@PostMapping(value="register")
	public ResponseParam<SysUser> register(@RequestBody SysUser sysUser) {
		SysUser save = userService.save(sysUser);
		return new ResponseParam<SysUser>("用户注册成功！", 200, save);
	}
	/**
	 * 用户登录
	 * @param loginUserVo
	 * @param request
	 * @return
	 */
	@PostMapping(value="login")
	public ResponseParam<LoginUserVo> login(@RequestBody LoginUserVo loginUserVo, HttpServletRequest request) {
		/*
		 * 判断登录用户
		 */
		Integer userRole = loginUserVo.getUserRole();
		HttpSession session = request.getSession();
		if (userRole == 0) {
			/*
			 * 普通用户登录
			 */
			SysUser login = userService.login(loginUserVo.getUserName(), loginUserVo.getPassword());
			if (login != null) {
				LoginUserVo vo = new LoginUserVo(login.getId(), login.getName(), login.getPwd(), 0);
				session.setAttribute("SESSION_USER", vo);
				return new ResponseParam<LoginUserVo>("登录成功!", 200, vo);
			}
		} else if (userRole == 1) {
			/*
			 * 超级管理员
			 */
			if ("admin".equals(loginUserVo.getUserName()) && "admin".equals(loginUserVo.getPassword())) {
				LoginUserVo vo = new LoginUserVo(0L, "admin", "admin", 1);
				session.setAttribute("SESSION_USER", vo);
				return new ResponseParam<LoginUserVo>("登录成功!", 200, vo);
			}
			/*
			 * 系统管理员登录
			 */
			SysAdminUser login = adminUserService.login(loginUserVo.getUserName(), loginUserVo.getPassword());
			if (login != null) {
				LoginUserVo vo = new LoginUserVo(login.getId(), login.getName(), login.getPwd(), 0);
				session.setAttribute("SESSION_USER", vo);
				return new ResponseParam<LoginUserVo>("登录成功!", 200, vo);
			}
		} else {
			return new ResponseParam<LoginUserVo>("请选择登录用户角色!", 500);
		}
		return new ResponseParam<LoginUserVo>("用户未授权!", 500);
	}

}
